/* Includes ----------------------------------------------------------------- */
#include "../bsp/bsp_usart.h"

#include <dma.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <usart.h>

/* Private define ----------------------------------------------------------- */
/* Private macro ------------------------------------------------------------ */
/* Private typedef ---------------------------------------------------------- */
#define BUFF_MAX_SIZE 128u
/* Private variables -------------------------------------------------------- */
static UartRx_t Rx;
uint8_t rx_buff[BUFF_MAX_SIZE];
uint8_t date[] = "Init Uart.\n";
/* Private function  -------------------------------------------------------- */
uint8_t UART_StartDMA(UartRx_t *uart) {
  return HAL_UART_Receive_DMA(uart->huart, rx_buff, BUFF_MAX_SIZE);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
  HAL_UART_Transmit(&huart2, date, sizeof(date), 1000);  // 把数据原封不动还给你
  HAL_UART_Receive_DMA(&huart2, rx_buff, BUFF_MAX_SIZE);  // 重新打开DMA接收数据
}

/* Exported functions ------------------------------------------------------- */
/**
 * @brief 串口初始化
 *
 * @param uart
 * @param huart
 */
void Uart_Init(UartRx_t *uart, UART_HandleTypeDef *huart) {
  if (huart == NULL) {
    Error_Handler();
  }
  uart->huart = huart;

  uart->rx_flag = false;
  uart->rx_len = 0;

  __HAL_UART_ENABLE_IT(uart->huart, UART_IT_IDLE);
  UART_StartDMA(uart);
}

/**
 * @brief 串口发送
 *
 * @param uart
 * @param tx_buff
 * @param len
 */
void Bsp_UartSendData(UartRx_t *uart, uint8_t *tx_buff, uint8_t len) {
  if (HAL_UART_Transmit_DMA(uart->huart, tx_buff, len) != HAL_OK) {
  }
}

/**
 * @brief 串口接收
 *
 * @param uart
 * @param rx_buff
 * @param len
 */
void Bsp_UartRecData(UartRx_t *uart, uint8_t *rx_buff, uint8_t len) {
  if (uart->rx_flag == true) {
    /* 开始接收已经发送完成数据 */
    HAL_UART_Transmit_DMA(uart->huart, rx_buff, len);
    memset(rx_buff, 0, uart->rx_len);
    uart->rx_flag = false;
    uart->rx_len = 0;
  }
  HAL_UART_Receive_DMA(uart->huart, rx_buff, BUFF_MAX_SIZE);
}
